package com.ruoyi.web.controller.prompt;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.task.domain.ModelParams;
import com.ruoyi.task.domain.SubBankServerConfig;
import com.ruoyi.task.service.IPromptService;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/prompt")
public class PromptController extends BaseController {

    @Autowired
    private IPromptService promptService;

    @PostMapping("/queryBranchBankConfig")
    @ResponseBody
    public AjaxResult queryBranchBankConfig() {
        try {
            List<SubBankServerConfig> result = promptService.queryBranchBankConfigList();
            logger.info("queryBranchBankConfig result = {}", JSON.toJSONString(result));
            return AjaxResult.success(result);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("queryBranchBankConfig error", e);
        }
        return AjaxResult.error("系统错误，请稍后再试！");
    }

    /**
     * 录像文件上传
     *
     * @param files
     * @param branchBank
     * @return
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("files") List<MultipartFile> files,
            @RequestParam("branchBank") String branchBank) {
        try {
            if (files.isEmpty() || files.size() > 10) {
                return AjaxResult.error("上传图片限制10个以内，视频仅支持1个");
            }
            boolean firstIsImage = true;

            // 判断文件大小， 文件类型
            for (int i = 0; i < files.size(); i++) {

                MultipartFile file = files.get(i);
                if (file.getSize() > 1024 * 1024 * 100) {
                    return AjaxResult.error("上传文件大小不能超过100M");
                }

                String filename = file.getOriginalFilename();
                if (!isImage(filename) && !isVideo(filename)) {
                    return AjaxResult.error("仅支持jpg, jpeg, png, mp4");
                }

                boolean currentIsImage = isImage(filename);
                if (i == 0) {
                    firstIsImage = currentIsImage;
                    if (isVideo(filename) && files.size() > 1) {
                        return AjaxResult.error("只允许上传1个视频");
                    }
                } else {
                    if (firstIsImage != currentIsImage) {
                        return AjaxResult.error("不支持同时上传图片和视频");
                    }
                }
            }

            String fileId = promptService.uploadFile(files, branchBank);
            logger.info("uploadFile fileId = {}", fileId);
            if (StringUtils.isNotEmpty(fileId)) {
                return AjaxResult.success("操作成功", fileId);
            }

        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("uploadFile error", e);
        }
        return AjaxResult.error("文件上传失败");
    }


    /**
     * 请求大模型结果
     *
     * @param paramForm
     * @return
     */
    @PostMapping("/aiModel")
    @ResponseBody
    public AjaxResult aiModel(@RequestBody ModelParams modelParams) {
        try {
            logger.info("aiModel params = {}", modelParams.toString());
            String result = promptService.requestModel(modelParams);
            logger.info("aiModel result = {}", result);
            if (StringUtils.isNotEmpty(result)) {
                return AjaxResult.success("操作成功", result);
            }
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("aiModel error", e);
        }
        return AjaxResult.error("系统错误，请稍后再试！");
    }





    /**
     * 判断文件是否是图片
     *
     * @param fileName
     * @return
     */
    private boolean isImage(String fileName) {

        // 获取文件扩展名（转换为小写）
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        // 定义支持的图片类型集合
        Set<String> imageExtensions = new HashSet<>();
        Collections.addAll(imageExtensions, "jpg", "jpeg", "png");
        // 判断是否是图片
        boolean isImage = imageExtensions.contains(extension);
        return isImage;
    }


    /**
     * 判断文件是否是视频
     *
     * @param fileName
     * @return
     */
    private boolean isVideo(String fileName) {

        // 获取文件扩展名（转换为小写）
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        // 定义支持的图片类型集合
        Set<String> videoExtensions = new HashSet<>();
        Collections.addAll(videoExtensions, "mp4", "avi", "wmv");
        // 判断是否是图片
        boolean isVideo = videoExtensions.contains(extension);
        return isVideo;
    }
}
